﻿using System;
using System.ComponentModel;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using System.Drawing;

namespace Havivi.FootballPool.AdminWebPart
{
    [ToolboxItemAttribute(false)]
    public class AdminWebPart : WebPart
    {
        private enum Result
        {
            Win = 0,
            Draw = 1,
            Loss = 2
        }
        protected override void CreateChildControls()
        {
            try
            {
                var web = SPContext.Current.Site.RootWeb;
                if (!web.UserIsWebAdmin)
                {
                    Controls.Add(new LiteralControl("You need to be a site administrator to view this webpart"));
                    return;
                }
                var siteUrl = SPContext.Current.Site.Url;
                var tableMain = new Table
                {
                    BorderStyle = BorderStyle.Solid,
                    BorderWidth = Unit.Pixel(1),
                    Width = Unit.Pixel(1280),
                    BackImageUrl = siteUrl + "/SiteAssets/Havivi.Euro2012/Images/backgroundEuro.jpg"
                };
                tableMain.Style.Add("background-repeat", "no-repeat");
                CreateMainHeader(tableMain);
                var rowMain = CreateEmptyCell();
                var cellMain = new TableCell { HorizontalAlign = HorizontalAlign.Left };
                var table = new Table { CssClass = "ms-listviewtable", CellPadding = 0, CellSpacing = 0 };
                CreateHeader(table);
                var itemsMatches = GetMatches(web);
                var alternatingstrong = false;
                var matchIndex = 0;
                foreach (SPListItem item in itemsMatches)
                {
                    matchIndex++;
                    var row = new TableRow();
                    if (alternatingstrong)
                        row.CssClass = "ms-alternatingstrong";
                    else
                        row.BackColor = Color.White;
                    CreateMatchRow(matchIndex, row, item, siteUrl);
                    switch (matchIndex)
                    {
                        case 25:
                            CreateQuarterFinals(table);
                            break;
                        case 29:
                            CreateSemiFinals(table);
                            break;
                        case 31:
                            CreateFinal(table);
                            break;
                    }
                    table.Rows.Add(row);
                    alternatingstrong = !alternatingstrong;
                }
                CreateButtonRow(table);
                cellMain.Controls.Add(table);
                rowMain.Cells.Add(cellMain);
                tableMain.Rows.Add(rowMain);
                Controls.Add(tableMain);
            }
            catch (Exception ex)
            {
                Controls.Add(new LiteralControl(ex.Message));
            }
        }

        private void CreateMatchRow(int matchIndex, TableRow row, SPListItem item, string siteUrl)
        {
            CreateIdCell(item, row);
            CreateDateCell(row, item);
            CreateTeamACell(matchIndex, row, item, siteUrl);
            CreateMinCell(row);
            CreateTeamBCell(matchIndex, row, item, siteUrl);

            var cell = new TableCell { HorizontalAlign = HorizontalAlign.Center };
            var btn = new Button();
            btn.Click += new EventHandler(this.Save_Click);
            btn.ID = "haviviBtnSave_" + matchIndex;
            btn.Text = "Save";
            btn.CssClass = "ms-ButtonHeightWidth";
            btn.Width = Unit.Pixel(88);
            cell.Controls.Add(btn);
            row.Cells.Add(cell);

            cell = new TableCell();
            cell.Controls.Add(new LiteralControl("&nbsp"));
            var btnUpdate = new Button();
            btnUpdate.Click += new EventHandler(this.Update_Click);
            btnUpdate.ID = "haviviBtnUpdate_" + matchIndex;
            btnUpdate.Text = "Update user's score";
            btnUpdate.CssClass = "ms-ButtonHeightWidth";
            btnUpdate.Width = Unit.Pixel(148);
            cell.Controls.Add(btnUpdate);
            cell.Controls.Add(new LiteralControl("&nbsp"));
            cell.Controls.Add(btnUpdate);
            CheckBox cb = new CheckBox();
            if (item["Disabled"] != null)
                cb.Checked = (bool)item["Disabled"];
            cb.ID = "haviviCBdis_" + matchIndex;
            cell.Controls.Add(new LiteralControl("&nbsp"));
            cell.Controls.Add(cb);
            row.Cells.Add(cell);
        }

        private static void CreateTeamBCell(int matchIndex, TableRow row, SPListItem item, string siteUrl)
        {
            var cell = new TableCell { CssClass = "ms-vb2", HorizontalAlign = HorizontalAlign.Left };
            var ddl = CreateDropDownList("HaviviAdmTeamScore2_", "ScoreB", matchIndex, item);
            cell.Controls.Add(ddl);
            if (matchIndex > 24)
            {
                ddl = new DropDownList { ID = "haviviDdlB_" + matchIndex, CssClass = "ms-RadioText" };
                ddl.Items.Add(new ListItem("", ""));
                ddl.Items.Add(new ListItem("Croatia", "Croatia"));
                ddl.Items.Add(new ListItem("Czech Republic", "Czech Republic"));
                ddl.Items.Add(new ListItem("Denmark", "Denmark"));
                ddl.Items.Add(new ListItem("England", "England"));
                ddl.Items.Add(new ListItem("France", "France"));
                ddl.Items.Add(new ListItem("Greece", "Greece"));
                ddl.Items.Add(new ListItem("Italy", "Italy"));
                ddl.Items.Add(new ListItem("Germany", "Germany"));
                ddl.Items.Add(new ListItem("Netherlands", "Netherlands"));
                ddl.Items.Add(new ListItem("Poland", "Poland"));
                ddl.Items.Add(new ListItem("Portugal", "Portugal"));
                ddl.Items.Add(new ListItem("Rep of Ireland", "Rep of Ireland"));
                ddl.Items.Add(new ListItem("Russia", "Russia"));
                ddl.Items.Add(new ListItem("Spain", "Spain"));
                ddl.Items.Add(new ListItem("Sweden", "Sweden"));
                ddl.Items.Add(new ListItem("Ukraine", "Ukraine"));

                if (item["TeamA"] != null)
                    ddl.SelectedValue = item["TeamA"].ToString();
                cell.Controls.Add(ddl);
            }
            else
            {
                if (item["FlagB"] != null)
                    cell.Controls.Add(new LiteralControl("&nbsp&nbsp<img src=\"" + siteUrl + "/SiteAssets/Havivi.Euro2012/Images/flags/" + item["FlagB"].ToString() + "\">&nbsp&nbsp"));
                if (item["TeamB"] != null)
                    cell.Controls.Add(new LiteralControl(item["TeamB"].ToString()));

            }
            row.Cells.Add(cell);
        }

        private static void CreateMinCell(TableRow row)
        {
            var cell = new TableCell();
            cell.Controls.Add(new LiteralControl(" - &nbsp"));
            row.Cells.Add(cell);
        }

        private static void CreateTeamACell(int matchIndex, TableRow row, SPListItem item, string siteUrl)
        {
            var cell = new TableCell { CssClass = "ms-vb2", HorizontalAlign = HorizontalAlign.Right };
            if (matchIndex > 24)
            {
                var ddl = new DropDownList { ID = "haviviDdlA_" + matchIndex, CssClass = "ms-RadioText" };
                ddl.Items.Add(new ListItem("", ""));
                ddl.Items.Add(new ListItem("Croatia", "Croatia"));
                ddl.Items.Add(new ListItem("Czech Republic", "Czech Republic"));
                ddl.Items.Add(new ListItem("Denmark", "Denmark"));
                ddl.Items.Add(new ListItem("England", "England"));
                ddl.Items.Add(new ListItem("France", "France"));
                ddl.Items.Add(new ListItem("Greece", "Greece"));
                ddl.Items.Add(new ListItem("Italy", "Italy"));
                ddl.Items.Add(new ListItem("Germany", "Germany"));
                ddl.Items.Add(new ListItem("Netherlands", "Netherlands"));
                ddl.Items.Add(new ListItem("Poland", "Poland"));
                ddl.Items.Add(new ListItem("Portugal", "Portugal"));
                ddl.Items.Add(new ListItem("Rep of Ireland", "Rep of Ireland"));
                ddl.Items.Add(new ListItem("Russia", "Russia"));
                ddl.Items.Add(new ListItem("Spain", "Spain"));
                ddl.Items.Add(new ListItem("Sweden", "Sweden"));
                ddl.Items.Add(new ListItem("Ukraine", "Ukraine"));

                if (item["TeamA"] != null)
                    ddl.SelectedValue = item["TeamA"].ToString();
                cell.Controls.Add(ddl);
            }
            else
            {

                if (item["TeamA"] != null)
                    cell.Controls.Add(new LiteralControl(item["TeamA"].ToString()));
                if (item["FlagA"] != null)
                    cell.Controls.Add(new LiteralControl("&nbsp&nbsp<img src=\"" + siteUrl + "/SiteAssets/Havivi.Euro2012/Images/flags/" + item["FlagA"].ToString() + "\">&nbsp&nbsp"));
            }
            var ddl1 = CreateDropDownList("HaviviAdmTeamScore1_", "ScoreA", matchIndex, item);
            cell.Controls.Add(ddl1);
            row.Cells.Add(cell);
        }

        private static void CreateDateCell(TableRow row, SPListItem item)
        {
            var cell = new TableCell { HorizontalAlign = HorizontalAlign.Left, CssClass = "ms-vb2" };
            if (item["MatcheDate"] != null)
            {
                var mDate = (DateTime)item["MatcheDate"];
                cell.Controls.Add(new LiteralControl("&nbsp&nbsp&nbsp&nbsp" + mDate.ToLongDateString() + " " + mDate.ToShortTimeString()));
            }
            row.Cells.Add(cell);
        }

        private static void CreateIdCell(SPListItem item, TableRow row)
        {
            var cell = new TableCell { HorizontalAlign = HorizontalAlign.Center };
            cell.Controls.Add(new LiteralControl(item["ID"].ToString()));
            row.Cells.Add(cell);
        }

        private static TableRow CreateEmptyCell()
        {
            var rowMain = new TableRow();
            var cellMain = new TableCell { Width = Unit.Pixel(232) };
            cellMain.Controls.Add(new LiteralControl("&nbsp&nbsp"));
            rowMain.Cells.Add(cellMain);
            return rowMain;
        }

        private static SPListItemCollection GetMatches(SPWeb web)
        {
            var list = web.Lists["HaviviMatches"];
            var query = new SPQuery
            {
                Query = "<OrderBy><FieldRef Name=\"MatcheDate\" Ascending=\"True\" /></OrderBy>",
                RowLimit = 31
            };
            return list.GetItems(query);
        }



        private static void CreateMainHeader(Table tableMain)
        {
            var rowMain = new TableRow();
            var cellMain = new TableCell { Height = Unit.Pixel(24), HorizontalAlign = HorizontalAlign.Left };
            cellMain.Controls.Add(new LiteralControl("&nbsp&nbsp<SPAN class=menu-item-text style=\"color: white\">Update Euro 2012 scores</SPAN>"));
            rowMain.Cells.Add(cellMain);

            cellMain = new TableCell { Height = Unit.Pixel(24), HorizontalAlign = HorizontalAlign.Right };
            rowMain.Cells.Add(cellMain);
            tableMain.Rows.Add(rowMain);
        }

        private static void CreateHeader(Table table)
        {
            var row = new TableRow { CssClass = "ms-viewheadertr" };
            var cell = new TableCell
            {
                HorizontalAlign = HorizontalAlign.Center,
                CssClass = "ms-vh2-nofilter ms-vh2-gridview"
            };
            cell.Controls.Add(new LiteralControl("<SPAN class=menu-item-text>#</SPAN>"));
            cell.Width = Unit.Pixel(30);
            row.Cells.Add(cell);
            cell = new TableCell
            {
                CssClass = "ms-vh2-nofilter ms-vh2-gridview",
                HorizontalAlign = HorizontalAlign.Left,
                Width = Unit.Pixel(254)
            };
            cell.Controls.Add(new LiteralControl("<SPAN class=menu-item-text>&nbsp&nbspTime</SPAN>"));
            row.Cells.Add(cell);
            cell = new TableCell
            {
                Width = Unit.Pixel(230),
                HorizontalAlign = HorizontalAlign.Right,
                CssClass = "ms-vh2-nofilter ms-vh2-gridview"
            };
            cell.Controls.Add(new LiteralControl("<SPAN class=menu-item-text>Team A</SPAN>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp"));
            row.Cells.Add(cell);

            cell = new TableCell { CssClass = "ms-vh2-nofilter ms-vh2-gridview" };
            cell.Controls.Add(new LiteralControl(" "));
            row.Cells.Add(cell);

            cell = new TableCell
            {
                Width = Unit.Pixel(230),
                CssClass = "ms-vh2-nofilter ms-vh2-gridview",
                HorizontalAlign = HorizontalAlign.Left
            };
            cell.Controls.Add(new LiteralControl("&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp<SPAN class=menu-item-text>Team B</SPAN>"));
            row.Cells.Add(cell);
            table.Rows.Add(row);

            cell = new TableCell { CssClass = "ms-vh2-nofilter ms-vh2-gridview" };
            cell.Controls.Add(new LiteralControl("<SPAN class=menu-item-text>Save</SPAN>&nbsp&nbsp"));

            row.Cells.Add(cell);

            cell = new TableCell { CssClass = "ms-vh2-nofilter ms-vh2-gridview" };
            cell.Controls.Add(new LiteralControl("&nbsp&nbsp"));
            row.Cells.Add(cell);

            row = new TableRow { CssClass = "ms-viewheadertr" };
            cell = new TableCell { ColumnSpan = 8, CssClass = "ms-vh2-nofilter ms-vh2-gridview" };
            cell.Controls.Add(new LiteralControl("<H3  class=\"ms-standardheader ms-WPTitle\" style=\"TEXT-ALIGN: justify;font-weight: normal\" ><NOBR><SPAN>&nbsp&nbspFirst Round</SPAN> </NOBR></H3>"));
            row.Cells.Add(cell);
            table.Rows.Add(row);
        }

        private static void CreateFinal(Table table)
        {
            var row = new TableRow { CssClass = "ms-viewheadertr" };
            var cell = new TableCell { ColumnSpan = 8, CssClass = "ms-vh2-nofilter ms-vh2-gridview" };
            cell.Controls.Add(new LiteralControl("<H3  class=\"ms-standardheader ms-WPTitle\" style=\"TEXT-ALIGN: justify;font-weight: normal\" ><NOBR><SPAN>&nbsp&nbspFinal</SPAN> </NOBR></H3>"));
            row.Cells.Add(cell);
            table.Rows.Add(row);
        }

        private static void CreateSemiFinals(Table table)
        {
            var row = new TableRow { CssClass = "ms-viewheadertr" };
            var cell = new TableCell { ColumnSpan = 8, CssClass = "ms-vh2-nofilter ms-vh2-gridview" };
            cell.Controls.Add(new LiteralControl("<H3  class=\"ms-standardheader ms-WPTitle\" style=\"TEXT-ALIGN: justify;font-weight: normal\" ><NOBR><SPAN>&nbsp&nbspSemi Finals</SPAN> </NOBR></H3>"));
            row.Cells.Add(cell);
            table.Rows.Add(row);
        }

        private static void CreateQuarterFinals(Table table)
        {
            var row = new TableRow { CssClass = "ms-viewheadertr" };
            var cell = new TableCell { ColumnSpan = 8, CssClass = "ms-vh2-nofilter ms-vh2-gridview" };
            cell.Controls.Add(new LiteralControl("<br /><H3  class=\"ms-standardheader ms-WPTitle\" style=\"TEXT-ALIGN: justify;font-weight: normal\" ><NOBR><SPAN>&nbsp&nbspQuarter Finals</SPAN> </NOBR></H3>"));
            row.Cells.Add(cell);
            table.Rows.Add(row);
        }

        private static DropDownList CreateDropDownList(string id, string scoreTeam, int matchIndex, SPListItem item)
        {
            var ddl = new DropDownList { ID = id + matchIndex, CssClass = "ms-RadioText" };
            ddl.Items.Add(new ListItem("", ""));
            ddl.Items.Add(new ListItem("0", "0"));
            ddl.Items.Add(new ListItem("1", "1"));
            ddl.Items.Add(new ListItem("2", "2"));
            ddl.Items.Add(new ListItem("3", "3"));
            ddl.Items.Add(new ListItem("4", "4"));
            ddl.Items.Add(new ListItem("5", "5"));
            ddl.Items.Add(new ListItem("6", "6"));
            ddl.Items.Add(new ListItem("7", "7"));
            ddl.Items.Add(new ListItem("8", "8"));
            ddl.Items.Add(new ListItem("9", "9"));
            ddl.Items.Add(new ListItem("*", "*"));

            if (item[scoreTeam] != null)
                ddl.SelectedValue = item[scoreTeam].ToString();
            return ddl;
        }

        void Save_Click(Object sender, EventArgs e)
        {
            SPWeb web = SPContext.Current.Site.RootWeb;
            string btnId = ((Button)sender).ID;
            string matchIndex = btnId.Substring(14);
            var list = web.Lists["HaviviMatches"];
            var query = new SPQuery
            {
                Query = string.Format("<Where><Eq><FieldRef Name=\"ID\" /><Value Type=\"Counter\">{0}</Value></Eq></Where>", matchIndex),
                RowLimit = 1
            };
            var items = list.GetItems(query);
            if (items.Count == 1)
            {
                var item = items[0];
                var teamScore1 = (DropDownList)FindControl("HaviviAdmTeamScore1_" + matchIndex);
                if (teamScore1.SelectedValue != string.Empty)
                    item["ScoreA"] = int.Parse(teamScore1.SelectedValue);
                var team1 = (DropDownList)FindControl("haviviDdlA_" + matchIndex);
                if (team1 != null)
                {
                    if (team1.SelectedValue != string.Empty)
                    {
                        item["TeamA"] = team1.SelectedValue;
                        item["FlagA"] = team1.SelectedValue.ToLower().Substring(0, 3) + ".png";
                    }
                }
                var teamScore2 = (DropDownList)FindControl("HaviviAdmTeamScore2_" + matchIndex);
                if (teamScore2.SelectedValue != string.Empty)
                    item["ScoreB"] = int.Parse(teamScore2.SelectedValue);
                var team2 = (DropDownList)FindControl("haviviDdlB_" + matchIndex);
                if (team2 != null)
                {
                    if (team2.SelectedValue != string.Empty)
                    {
                        item["TeamB"] = team2.SelectedValue;
                        item["FlagB"] = team2.SelectedValue.ToLower().Substring(0, 3) + ".png";
                    }
                }
                var cb = (CheckBox)FindControl("haviviCBdis_" + matchIndex);
                if (cb != null)
                {
                    item["Disabled"] = cb.Checked;
                }
                item.Update();
            }

        }

        private void CreateButtonRow(Table table)
        {
            var row = new TableRow();
            var cell = new TableCell { ColumnSpan = 2 };
            var btn = new Button();
            btn.Click += new EventHandler(this.ShowLists_Click);

            btn.Text = "Show lists";
            btn.CssClass = "ms-ButtonHeightWidth";
            btn.Width = Unit.Pixel(100);
            cell.Controls.Add(btn);
            row.Cells.Add(cell);

            btn = new Button();
            btn.Click += new EventHandler(this.HideLists_Click);

            btn.Text = "Hide lists";
            btn.CssClass = "ms-ButtonHeightWidth";
            btn.Width = Unit.Pixel(100);
            cell.Controls.Add(btn);
            row.Cells.Add(cell);


            cell = new TableCell { HorizontalAlign = HorizontalAlign.Right, ColumnSpan = 3 };
            btn = new Button();
            btn.Click += new EventHandler(this.UpdateStandings_Click);

            btn.Text = "Update user's standings";
            btn.CssClass = "ms-ButtonHeightWidth";
            btn.Width = Unit.Pixel(188);
            cell.Controls.Add(btn);



            cell.Style.Add("padding-right", "196px");
            row.Cells.Add(cell);

            cell = new TableCell { ColumnSpan = 3 };
            row.Cells.Add(cell);
            table.Rows.Add(row);
        }


        void ShowLists_Click(Object sender, EventArgs e)
        {
            SPWeb web = SPContext.Current.Site.RootWeb;
            SPList list = web.Lists.TryGetList("Euro 2012 Standings");
            list.OnQuickLaunch = true;
            list.Hidden = false;


            list.DisableGridEditing = false;
            EnabeldField(list, "Name");
            EnabeldField(list, "Score");
            EnabeldField(list, "User");
            EnabeldField(list, "Position");
            SPView view = list.DefaultView;
            view.ViewFields.DeleteAll();
            view.Update();
            SPField filedName = list.Fields["Name"];
            filedName.LinkToItem = true;
            filedName.LinkToItemAllowed = SPField.ListItemMenuState.Required;
            filedName.ListItemMenu = true;
            filedName.ListItemMenuAllowed = SPField.ListItemMenuState.Required;
            filedName.Update();
            SPField filedScore = list.Fields["Score"];
            SPField filedUser = list.Fields["User"];
            SPField filedPosition = list.Fields["Position"];
            view.ViewFields.Add(filedName);
            view.ViewFields.Add(filedUser);
            view.ViewFields.Add(filedScore);
            view.ViewFields.Add(filedPosition);
            view.Update();
            list.Update();

            list = web.Lists.TryGetList("HaviviMatches");
            list.OnQuickLaunch = true;
            list.Hidden = false;
            list.DisableGridEditing = false;
            EnabeldField(list, "Disabled");
            EnabeldField(list, "TeamA");
            EnabeldField(list, "TeamB");
            EnabeldField(list, "ScoreA");
            EnabeldField(list, "ScoreB");
            EnabeldField(list, "FlagA");
            EnabeldField(list, "FlagB");
            EnabeldField(list, "MatcheDate");
            EnabeldField(list, "Info");
              view = list.DefaultView;
            view.ViewFields.DeleteAll();
            view.Update();
            SPField filedTeamA = list.Fields["TeamA"];
            filedTeamA.LinkToItem = true;
            filedTeamA.LinkToItemAllowed = SPField.ListItemMenuState.Required;
            filedTeamA.ListItemMenu = true;
            filedTeamA.ListItemMenuAllowed = SPField.ListItemMenuState.Required;
            filedTeamA.Update();
            SPField Disabled = list.Fields["Disabled"];
            view.ViewFields.Add(Disabled);
            SPField TeamB = list.Fields["TeamB"];
            view.ViewFields.Add(filedTeamA);
            view.ViewFields.Add(TeamB);
            view.Update();
            list.Update();

            list = web.Lists.TryGetList("HaviviUserMatches");
            list.OnQuickLaunch = true;
            list.Hidden = false;
            list.DisableGridEditing = false;
            EnabeldField(list, "User");
            EnabeldField(list, "Match");
            EnabeldField(list, "ScoreTeamA");
            EnabeldField(list, "ScoreTeamB");
            EnabeldField(list, "Score");
            EnabeldField(list, "DispName");
            view = list.DefaultView;
            view.ViewFields.DeleteAll();
            view.Update();
            SPField fUser = list.Fields["User"];
            fUser.LinkToItem = true;
            fUser.LinkToItemAllowed = SPField.ListItemMenuState.Required;
            fUser.ListItemMenu = true;
            fUser.ListItemMenuAllowed = SPField.ListItemMenuState.Required;
            fUser.Update();
            SPField fMatch = list.Fields["Match"];
            SPField fDispName = list.Fields["DispName"];
            view.ViewFields.Add(fUser);
            view.ViewFields.Add(fMatch);
            view.ViewFields.Add(fDispName);
            view.Update();
            list.Update();
        }

        void HideLists_Click(Object sender, EventArgs e)
        {
            SPWeb web = SPContext.Current.Site.RootWeb;
            SPList list = web.Lists.TryGetList("Euro 2012 Standings");
            list.OnQuickLaunch = false;
            list.Hidden = true;
            list.NoCrawl = true;
            list.DisableGridEditing = true;
            DisabeldField(list, "Name");
            DisabeldField(list, "Score");
            DisabeldField(list, "User");
            DisabeldField(list, "Position");
            SPView view = list.DefaultView;
            view.ViewFields.DeleteAll();
            view.Update();
            list.Update();

            list = web.Lists.TryGetList("HaviviMatches");
            list.OnQuickLaunch = false;
            list.Hidden = true;
            list.NoCrawl = true;
            list.DisableGridEditing = true;
            DisabeldField(list, "TeamA");
            DisabeldField(list, "TeamB");
            DisabeldField(list, "ScoreA");
            DisabeldField(list, "ScoreB");
            DisabeldField(list, "FlagA");
            DisabeldField(list, "FlagB");
            DisabeldField(list, "MatcheDate");
            DisabeldField(list, "Info");
            view = list.DefaultView;
            view.ViewFields.DeleteAll();
            view.Update();
            list.Update();

            list = web.Lists.TryGetList("HaviviUserMatches");
            list.OnQuickLaunch = false;
            list.NoCrawl = true;
            list.Hidden = true;
            list.DisableGridEditing = true;
            DisabeldField(list, "User");
            DisabeldField(list, "Match");
            DisabeldField(list, "ScoreTeamA");
            DisabeldField(list, "ScoreTeamB");
            DisabeldField(list, "Score");
            DisabeldField(list, "DispName");
            view = list.DefaultView;
            view.ViewFields.DeleteAll();
            view.Update();
            list.Update();
        }

        private static void DisabeldField(SPList list, string name)
        {
            SPField field = list.Fields[name];

            field.ShowInViewForms = false;
            field.ShowInNewForm = false;
            field.ShowInEditForm = false;
            field.ShowInListSettings = false;
            field.ReadOnlyField = true;
            field.Update();
        }

        private static void EnabeldField(SPList list, string name)
        {
            SPField field = list.Fields[name];
            field.ShowInViewForms = true;
            field.ShowInNewForm = true;
            field.ShowInEditForm = true;
            field.ShowInListSettings = true;
            field.ReadOnlyField = false;
            field.Update();
        }

        void UpdateStandings_Click(Object sender, EventArgs e)
        {
            SPWeb web = SPContext.Current.Site.RootWeb;
            var listUserMatches = web.Lists["HaviviUserMatches"];
            var query = new SPQuery
             {
                 Query = "<Where><And><IsNotNull><FieldRef Name=\"Score\" /></IsNotNull><Neq><FieldRef Name=\"Score\" /><Value Type=\"Number\">0</Value></Neq></And></Where><OrderBy><FieldRef Name=\"User\" Ascending=\"True\" /></OrderBy>"
             };
            var listUserMatchesItems = listUserMatches.GetItems(query);
            string curUser = string.Empty;
            string nexUser = string.Empty;

            int totalUserScore = 0;
            int totalItems = listUserMatchesItems.Count;
            int index = 0;
            foreach (SPListItem userMatche in listUserMatchesItems)
            {
                index++;
                int score = 0;
                if (userMatche["User"] != null)
                    curUser = userMatche["User"].ToString();
                if (index < totalItems)
                {
                    if (listUserMatchesItems[index]["User"] != null)
                        nexUser = listUserMatchesItems[index]["User"].ToString();

                }
                if (nexUser == curUser && index < totalItems)
                {

                    if (userMatche["Score"] != null)
                        score = int.Parse(userMatche["Score"].ToString());
                    totalUserScore += score;
                }
                else
                {
                    if (userMatche["Score"] != null)
                        score = int.Parse(userMatche["Score"].ToString());
                    totalUserScore += score;
                    var list = web.Lists["Euro 2012 Standings"];
                    query = new SPQuery
                    {
                        Query = string.Format("<Where><Eq><FieldRef Name=\"User\" /><Value Type=\"Text\">{0}</Value></Eq></Where>", curUser),
                        RowLimit = 1
                    };
                    var items = list.GetItems(query);

                    if (items.Count > 0)
                    {
                        var item = items[0];
                        item["Score"] = totalUserScore;
                        item.Update();
                    }
                    totalUserScore = 0;
                }
            }
        }

        void Update_Click(Object sender, EventArgs e)
        {
            SPWeb web = SPContext.Current.Site.RootWeb;
            string btnId = ((Button)sender).ID;
            string matchIndex = btnId.Substring(16);
            var list = web.Lists["HaviviMatches"];
            var query = new SPQuery
            {
                Query = string.Format("<Where><Eq><FieldRef Name=\"ID\" /><Value Type=\"Counter\">{0}</Value></Eq></Where>", matchIndex),
                RowLimit = 1
            };
            var items = list.GetItems(query);
            if (items.Count == 1)
            {
                var score1 = 99;
                var score2 = 99;


                var item = items[0];
                if (item["ScoreA"] != null)
                    score1 = int.Parse(item["ScoreA"].ToString());
                if (item["ScoreB"] != null)
                    score2 = int.Parse(item["ScoreB"].ToString()); ;
                if (score1 != 99 && score2 != 99)
                {
                    Result result;
                    if (score1 == score2)
                        result = Result.Draw;
                    else if (score1 > score2)
                        result = Result.Win;
                    else
                        result = Result.Loss;
                    var listUserMatches = web.Lists["HaviviUserMatches"];
                    query = new SPQuery
                    {
                        Query = string.Format("<Where><Eq><FieldRef Name=\"Match\" /><Value Type=\"Number\">{0}</Value></Eq></Where>", matchIndex),
                    };
                    var listUserMatchesItems = listUserMatches.GetItems(query);
                    foreach (SPListItem userMatche in listUserMatchesItems)
                    {
                        var totalScore = 0;
                        var userScore1 = 99;
                        var userScore2 = 99;
                        if (userMatche["ScoreTeamA"] != null)
                            userScore1 = int.Parse(userMatche["ScoreTeamA"].ToString());
                        if (userMatche["ScoreTeamB"] != null)
                            userScore2 = int.Parse(userMatche["ScoreTeamB"].ToString());
                        if (userScore1 != 99 && userScore2 != 99)
                        {
                            Result resultUser;
                            if (userScore1 == userScore2)
                                resultUser = Result.Draw;
                            else if (userScore1 > userScore2)
                                resultUser = Result.Win;
                            else
                                resultUser = Result.Loss;

                            if (userScore1 == score1)
                                totalScore += 2;
                            if (userScore2 == score2)
                                totalScore += 2;
                            if (userScore1 == score1 && userScore2 == score2)
                                totalScore += 1;
                            if (resultUser == result)
                                totalScore += 5;
                            userMatche["Score"] = totalScore;
                            userMatche.Update();
                        }
                    }
                }
            }
        }
    }
}
